<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>框选获取瓦片-只要18级</title>
    <script src="/Public/js/tianditu.api.js"></script>
    <script src="/Public/js/jquery-3.7.1.min.js"></script>
    <script src="/Public/js/three_utills.js"></script>
    <link rel="icon" href="/Public/imgs/H.ico">
    <style>
        html,
        body {
            margin: 0;
            padding: 0;
            width: 100%;
            height: 100%;
            overflow: hidden;
        }

        #map {
            position: relative;
            width: 100%;
            height: 100%;
        }

        #getDem {
            position: absolute;
            bottom: 100px;
            left: 20px;
            z-index: 450;
            width: 50px;
            height: 200x;
        }

        #canvas1 {
            position: absolute;
            top: 50px;
            left: 50px;
            z-index: 450;
            /* width:500px; */
            /* height:500px */
        }

        #canvas2 {
            position: absolute;
            top: 50px;
            right: 50px;
            z-index: 450;
        }
    </style>
</head>

<body>
    <div id="map"></div>
    <canvas id="canvas1"></canvas>
    <canvas id="canvas2"></canvas>
    <button id="getDem">T</button>

    <script>
        var map = new T.Map('map', { tileSize: 256 });
        map.centerAndZoom(new T.LngLat(103, 30), 18);
        var ctrl = new T.Control.MapType(
            { position: T_ANCHOR_BOTTOM_RIGHT }
        );
        map.addControl(ctrl);

        var recTool = new T.RectangleTool(map, { showLabel: false });

        $('#getDem').on('click', HD1)

        function HD1() {
            recTool.removeEventListener('draw');
            recTool.clear();
            recTool.open();
            recTool.addEventListener('draw', (e) => {
                const zoom = 18;
                const tileSize = 256;

                var minX = e.currentBounds.getSouthWest().lng
                var minY = e.currentBounds.getSouthWest().lat
                var maxX = e.currentBounds.getNorthEast().lng
                var maxY = e.currentBounds.getNorthEast().lat

                const nw = lngLatToTile(minX, maxY, zoom);  // 西北角
                const ne = lngLatToTile(maxX, maxY, zoom);  // 东北角
                const sw = lngLatToTile(minX, minY, zoom);  // 西南角
                const se = lngLatToTile(maxX, minY, zoom);

                const minCol = Math.min(nw[0], sw[0]);
                const maxCol = Math.max(ne[0], se[0]);
                const minRow = Math.min(ne[1], se[1]);  // 注意：行号从上到下增加
                const maxRow = Math.max(nw[1], sw[1]);

                const tiles = [];
                for (let col = minCol; col <= maxCol; col++) {
                    for (let row = minRow; row <= maxRow; row++) {
                        tiles.push({
                            url: getTileWMTSUrlIMG(col, row, zoom),
                            col: col,
                            row: row,
                        });
                    }
                }

                const bounds = calculateBounds(tiles);
                const canvasWidth = (bounds.maxCol - bounds.minCol + 1) * tileSize;
                const canvasHeight = (bounds.maxRow - bounds.minRow + 1) * tileSize;

                const canvas = $('#canvas1')[0];
                const ctx = canvas.getContext('2d', { willReadFrequently: true });
                canvas.width = canvasWidth;
                canvas.height = canvasHeight;
                ctx.fillStyle = 'transparent';
                ctx.fillRect(0, 0, canvasWidth, canvasHeight);

                //计算第一个瓦片左上角坐标
                const [firstTile_nw_x, firstTile_nw_y] = tileToLngLat(minCol, minRow, zoom);
                //计算最后一个瓦片右下角坐标,+1保证为右下角(否则为最后一个瓦片的左上角坐标)
                const [lastTile_se_x, lastTile_se_y] = tileToLngLat(maxCol + 1, maxRow + 1, zoom);
                //计算范围宽高
                const geoWidth = lastTile_se_x - firstTile_nw_x;
                const geoHeight = lastTile_se_y - firstTile_nw_y;
                //计算像素比例
                const pixelsPerDegreeX = canvasWidth / geoWidth;
                const pixelsPerDegreeY = canvasHeight / geoHeight;
                //计算选择框像素尺寸
                const selectionPixelWidth = (maxX - minX) * pixelsPerDegreeX;
                const selectionPixelHeight = (minY - maxY) * pixelsPerDegreeY;

                console.log(canvasWidth,geoWidth)

                const canvas2 = $('#canvas2')[0];
                canvas2.width = Math.ceil(selectionPixelWidth);
                canvas2.height = Math.ceil(selectionPixelHeight);
                const ctx2 = canvas2.getContext('2d');

                // 计算偏移量
                const offset_x = (minX - firstTile_nw_x) * pixelsPerDegreeX;
                const offset_y = (maxY - firstTile_nw_y) * pixelsPerDegreeY;

                getAllImages(tiles).then(images => {
                    images.forEach((img, index) => {
                        const tile = tiles[index];
                        const x = (tile.col - bounds.minCol) * tileSize;
                        const y = (tile.row - bounds.minRow) * tileSize;
                        ctx.drawImage(img, x, y, tileSize, tileSize);
                    });

                    const imageData = ctx.getImageData(
                        Math.floor(offset_x),
                        Math.floor(offset_y),
                        canvas2.width,
                        canvas2.height
                    );
                    ctx2.putImageData(imageData, 0, 0);


                });
            })

        }
    </script>
</body>

</html>